package com.ibl.rover.lite.client;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.ibl.rover.lite.client.Application.ApplicationContext;

import android.os.Environment;
import android.text.LoginFilter;

public class Logger {

	public static ApplicationContext roverApp;
	private static boolean externalStorageAvailable = false;
	private static FileWriter logFile = null;
	private static boolean isInitialized = false;
	private static final String ROVER_LITE_LOG = "rover_lite_log.txt";
	private static final String lineSeparator = System
			.getProperty("line.separator");
	private static final Logger logger = new Logger();
	private static String debugDateFormat = "";
	private Formatter formatter = new Formatter();

	public synchronized void log(final String infoMsg) {
		if (externalStorageAvailable) {
			try {
 				SimpleDateFormat dateFormat = new SimpleDateFormat(
						debugDateFormat);
				String deviceDate = "[" + dateFormat.format(new Date()) + "]";
				logFile.write(deviceDate + infoMsg + lineSeparator);
				logFile.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public synchronized void logException(final String logMsg, Exception ex) {
		if (externalStorageAvailable) {
			try {
				logFile.write(logMsg
						+ " : "
						+ formatter.format(ex.getMessage(),
								ex.fillInStackTrace()) + "]" + lineSeparator);
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						debugDateFormat);
				String deviceDate = "[" + dateFormat.format(new Date()) + "]";
				logFile.write(deviceDate + logMsg + " : " + ex.getMessage()
						+ "]" + lineSeparator);
				logFile.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static Logger getLogger() {
		return logger;
	}

	public static void init(ApplicationContext roverApp) {
		if (!isInitialized) {
			String externalState = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(externalState)) {
				externalStorageAvailable = true;
				File rootPath = Environment.getExternalStorageDirectory();
				rootPath.canWrite();
//				rootPath.setWritable(true);
				if (null != rootPath) {
					try {
						File logFileCreation = null;
						debugDateFormat = roverApp.getAppParams()
								.getDebugDateFormat();
						String loggingPath = roverApp.getAppParams()
								.getLoggingPath();
						
						String logFilePath = rootPath.getAbsolutePath()
								+ loggingPath;
						File logFileDirectotry = new File(logFilePath);
					
						if (!logFileDirectotry.exists()) {
							logFileDirectotry.mkdirs();
						}
						logFileCreation = new File(logFilePath + ROVER_LITE_LOG);
						if (!logFileCreation.exists()) {
							logFileCreation.createNewFile();
						}
						logFile = new FileWriter(logFileCreation);
					} catch (IOException ex) {
						ex.printStackTrace();

					}
				}
			}
			isInitialized = true;
		}
	}

}
